<template>
  <page-view class="page-view" :title="false">
    <div slot="headerContent">
      <a-breadcrumb class="s-breadcrumb">
        <a-breadcrumb-item>资产管理</a-breadcrumb-item>
        <a-breadcrumb-item><router-link to="/property/plan">资产盘点计划</router-link></a-breadcrumb-item>
        <a-breadcrumb-item>{{ name }}</a-breadcrumb-item>
      </a-breadcrumb>
    </div>

    <a-card class="s-card">
      <a-spin :spinning="sending">

        <a-tabs v-model="tabIndex" animated type="card">
          <a-tab-pane :key="0" tab="子计划详情">

            <div class="filter">
              <a-form>
                <a-row>
                  <a-col :lg="8" :md="12" :sm="24">
                    <a-form-item label="子计划名称" v-bind="formItemLayout" class="label-width-auto">
                      <a-input v-model="queryParam.name" placeholder="请输入" />
                    </a-form-item>
                  </a-col>
                  <a-col :lg="8" :md="12" :sm="24">
                    <a-form-item label="截止日期" v-bind="formItemLayout">
                      <a-range-picker v-model="dateSection" allow-clear />
                    </a-form-item>
                  </a-col>
                  <a-col :lg="8" :xs="0">
                    <a-button type="primary" @click="handlePage()">查询</a-button>
                    <a-button @click="reset">重置</a-button>
                  </a-col>
                </a-row>
                <a-row>
                  <a-col :lg="0" :md="24">
                    <div class="btn-container">
                      <a-button type="primary" @click="handlePage()">查询</a-button>
                      <a-button @click="reset">重置</a-button>
                      <a-button type="primary" @click="handleAdd"><a-icon type="plus" />新增子计划</a-button>
                    </div>
                  </a-col>
                  <a-col :lg="8" :xs="0">
                    <div class="btn-container">
                      <a-button type="primary" @click="handleAdd"><a-icon type="plus" />新增子计划</a-button>
                    </div>
                  </a-col>
                </a-row>
              </a-form>
            </div>

            <s-table
              ref="table"
              class="s-table"
              bordered
              row-key="id"
              :locale="{ emptyText: '暂无数据' }"
              :show-pagination="false"
              :columns="columns"
              :data="loadData"
              :scroll="{ y: scrollY }"
              :alert="false"
            >
              <template slot="check" slot-scope="item">
                <span class="success-link" @click="showDetail(item, true)">查看</span>
              </template>
              <template slot="completeness" slot-scope="item">
                <a-progress :percent="item.completeness * 100" size="small" />
              </template>
              <template slot="action" slot-scope="item">
                <div class="action-container between">
                  <span class="success-link" @click="showDetail(item)">详情</span>
                  <span v-if="item.completeness >= 1 && item.status < 3" class="primary-link" style="padding: 0;" @click="handleFinish(item)">完成盘点</span>
                  <span class="danger-link" @click="handleDel(item)">删除</span>
                </div>
              </template>
            </s-table>

          </a-tab-pane>

          <a-tab-pane :key="1" tab="盘点汇总明细" style="position: relative">
            <a-tabs v-model="detailTabIndex" animated type="card">
              <template slot="tabBarExtraContent">
                <a-button class="primary-btn" :loading="sending" @click="handleExport">导出报表</a-button>
              </template>
              <a-tab-pane :key="0" tab="盘点汇总表">
                <s-table
                  ref="childTable-0"
                  class="s-table"
                  bordered
                  :columns="allColumns"
                  :data="loadAll"
                  :locale="{ emptyText: '暂无数据' }"
                  :show-pagination="false"
                  :alert="false"
                  :scroll="{ y: scrollYDetail }"
                  row-key="k"
                >
                  <template slot="action" slot-scope="item">
                    <div class="action-container">
                      <span class="success-link" @click="showDataDetail(item)">详情</span>
                    </div>
                  </template>
                  <template slot="footer">
                    <a-table
                      v-if="$get(countAll, 'length')"
                      class="s-table footer-table"
                      bordered
                      :columns="allColumns"
                      :scroll="{ y: scrollYDetail }"
                      :data-source="countAll"
                      :show-header="false"
                      :pagination="false"
                      row-key="name"
                    >
                      <template slot="action">
                        <div class="action-container">
                          <div style="opacity: 0; width:100%;" />
                        </div>
                      </template>
                    </a-table>
                  </template>
                </s-table>
              </a-tab-pane>

              <a-tab-pane
                v-for="(tab, index) in childList"
                :key="index + 1"
                :tab="`${tab.name}汇总表`"
              >
                <s-table
                  :ref="`childTable-${detailTabIndex}`"
                  class="s-table"
                  bordered
                  :columns="childColumns"
                  :data="loadAll"
                  :locale="{ emptyText: '暂无数据' }"
                  :show-pagination="false"
                  :alert="false"
                  :scroll="{ y: scrollYDetail }"
                  row-key="k"
                >
                  <template slot="action" slot-scope="item">
                    <div class="action-container">
                      <span class="success-link" @click="showDataDetail(item)">详情</span>
                    </div>
                  </template>
                  <template slot="footer">
                    <a-table
                      v-if="countChild[detailTabIndex] && countChild[detailTabIndex].length"
                      class="s-table footer-table"
                      bordered
                      :columns="childColumns"
                      :scroll="{ y: scrollYDetail }"
                      :data-source="countChild[detailTabIndex]"
                      :show-header="false"
                      :pagination="false"
                      row-key="name"
                    />
                  </template>
                </s-table>
              </a-tab-pane>
            </a-tabs>
          </a-tab-pane>

        </a-tabs>

      </a-spin>
    </a-card>

    <a-modal
      v-model="showDataModal"
      title="物品明细"
      centered
      :footer="null"
      width="80%"
    >
      <a-table
        class="s-table"
        bordered
        :scroll="{ y: 400 }"
        :columns="detailColumns"
        :data-source="targetList"
        :locale="{ emptyText: '暂无数据' }"
        :pagination="false"
        row-key="name"
      >
        <template slot="footer">
          <a-table
            class="s-table footer-table"
            bordered
            :columns="detailColumns"
            :data-source="detailCount"
            :scroll="{ y: 400 }"
            :show-header="false"
            :pagination="false"
            row-key="name"
          />
        </template>
      </a-table>
    </a-modal>

  </page-view>
</template>

<script>
import { PageView, STable } from '@/components'

export default {
  name: 'Child',
  components: { PageView, STable },
  inject: ['formItemLayout'],
  props: {
    name: {
      type: String,
      default: ''
    },
    id: {
      type: String,
      default: ''
    }
  },
  validate ({ params }) { return params.name && params.id },

  data () {
    return {
      sending: false,
      tabIndex: 0,
      detailTabIndex: 0,
      scrollY: 500,
      scrollYDetail: 400,
      dateSection: [],

      queryParam: {
        pageNum: -1,
        pid: this.id / 1,
        deadlineEnd: undefined,
        deadlineStart: undefined
      },

      columns: [
        { title: '子计划名称', align: 'center', dataIndex: 'name' },
        { title: '盘点资产', width: '105px', align: 'center', scopedSlots: { customRender: 'check' }},
        { title: '盘点区域数量', width: '15%', align: 'center', dataIndex: 'detailCount' },
        { title: '截止日期', width: '15%', align: 'center', dataIndex: 'deadline' },
        { title: '完成度', width: '20%', align: 'center', scopedSlots: { customRender: 'completeness' }},
        { title: '操作', align: 'center', width: '160px', scopedSlots: { customRender: 'action' }}
      ],
      childList: [],

      allColumns: [
        { title: '盘点子计划', align: 'center', width: '15%', dataIndex: 'planName' },
        { title: '资产名称', align: 'center', width: '15%', dataIndex: 'goodsName' },
        { title: '上期结存', align: 'center', width: '10%', dataIndex: 'lastBalance' },
        { title: '本期领入', align: 'center', width: '10%', dataIndex: 'receive' },
        { title: '本期减少', align: 'center', width: '10%', dataIndex: 'reduce' },
        { title: '上报数量', align: 'center', width: '10%', dataIndex: 'quantity' },
        { title: '本期结存', align: 'center', width: '10%', dataIndex: 'balance' },
        { title: '库存状态', align: 'center', width: '10%', dataIndex: 'status' },
        { title: '操作', align: 'center', scopedSlots: { customRender: 'action' }}
      ],
      countAll: [],

      childColumns: [
        { title: '物品编号', align: 'center', width: '15%', dataIndex: 'code' },
        { title: '物品名称', align: 'center', width: '15%', dataIndex: 'goodsName' },
        { title: '盘点区域', align: 'center', width: '10%', dataIndex: 'deptName' },
        { title: '上期结存', align: 'center', width: '10%', dataIndex: 'lastBalance' },
        { title: '本期领入', align: 'center', width: '10%', dataIndex: 'receive' },
        { title: '本期减少', align: 'center', width: '10%', dataIndex: 'reduce' },
        { title: '本期结存', align: 'center', width: '10%', dataIndex: 'balance' },
        { title: '库存状态', align: 'center', width: '10%', dataIndex: 'status' },
        { title: '操作', align: 'center', scopedSlots: { customRender: 'action' }}
      ],
      countChild: [[]],

      showDataModal: false,
      detailColumns: [
        { title: '盘点物品', align: 'center', width: '15%', dataIndex: 'goodsName' },
        { title: '盘点区域', align: 'center', width: '15%', dataIndex: 'deptName' },
        { title: '上期结存', align: 'center', width: '10%', dataIndex: 'lastBalance' },
        { title: '本期领入', align: 'center', width: '10%', dataIndex: 'receive' },
        { title: '本期减少', align: 'center', width: '10%', dataIndex: 'reduce' },
        { title: '上报数量', align: 'center', width: '10%', dataIndex: 'quantity' },
        { title: '本期结存', align: 'center', width: '10%', dataIndex: 'balance' },
        { title: '盘点负责人', align: 'center', dataIndex: 'userName' }
      ],
      targetList: [],
      detailCount: []
    }
  },

  watch: {
    detailTabIndex (index) {
      this.refresh(`childTable-${index}`)
    }
  },

  mounted () {
    if (!process.client) return false
    const viewHeight = document.querySelector('.ant-layout-content').offsetHeight
    this.scrollY = viewHeight - 64 - 55 - 12 * 2 - 24 * 2 - 40 - 102 - 62
    this.scrollYDetail = viewHeight - 64 - 55 - 12 * 2 - 24 * 2 - 56 * 2 - 62 - 54
    if (this.scrollY < 0) this.scrollY = 500
    if (this.scrollYDetail < 0) this.scrollYDetail = 400
  },

  methods: {
    async handleExport () {
      const { detailTabIndex, $moment, childList, id, $message } = this
      $message.destroy()
      if (!childList || !childList.length) return $message.error('没有可导出数据，请刷新或稍后再试')
      const nowTime = $moment().format('YYYY-MM-DD HH:mm:ss')
      const param = { id: id / 1 }
      if (detailTabIndex) param.cli_id = childList[detailTabIndex - 1].id
      const name = ['盘点', ...childList.map(i => i.name)][detailTabIndex]
      this.$toggleSending(1)
      await this.$exportFile({
        url: `api/assetsInventory/exportqueryPlan`,
        param,
        fileName: `${name}汇总表_${nowTime}`
      })
      this.$toggleSending()
    },

    loadAll () {
      const { $axios, $get, id, countAll, detailTabIndex, childList, countChild } = this
      const resData = { data: [] }
      const param = { id: id / 1 }
      if (detailTabIndex) param.cli_id = childList[detailTabIndex - 1].id
      const count = detailTabIndex ? countChild : countAll
      if (detailTabIndex) count.splice(detailTabIndex, 1, [])
      else count.splice(0)
      return $axios.post('api/assetsInventory/queryPlan', param)
        .then(res => {
          const list = $get(res, 'data.data', [])
          resData.data = list.filter(i => i.code !== '小计').map((i, k) => {
            const data = { k }
            const keys = ['goodsName', 'code', 'deptName']
            keys.forEach(key => { if (!i[key]) data[key] = '-' })
            if (!i.quantity) data.quantity = 0
            return Object.assign(i, data)
          })
          const countList = list.filter(i => i.code === '小计').map(i => Object.assign(i, { planName: '小计' }))
          if (detailTabIndex) count.splice(detailTabIndex, 1, countList)
          else count.push(...countList)
          return resData
        }).catch(e => resData)
    },

    loadData () {
      const { queryParam, childList, $axios, id, $get, $moment, dateSection } = this
      const params = {}
      for (const key in queryParam) {
        const item = queryParam[key]
        if (item) params[key] = item
      }
      params.pid = id / 1
      if ($get(dateSection, 'length') > 1) {
        params.deadlineStart = dateSection[0].format('YYYY-MM-DD')
        params.deadlineEnd = dateSection[1].format('YYYY-MM-DD')
      }
      const resData = { data: [] }
      childList.splice(0)

      return $axios.post('api/assetsInventoryPlan/childQuery', params).then(res => {
        resData.data = $get(res, 'data.data.dataList', []).map(i => {
          const deadlineDate = i.deadline ? $moment(i.deadline).format('YYYY.MM.DD') : '暂无'
          return Object.assign(i, { deadlineDate })
        })
        childList.push(...resData.data)
        return resData
      }).catch(e => resData)
    },

    reset () {
      this.dateSection = []
      Object.assign(this.queryParam, { name: undefined, deadlineStart: undefined, deadlineEnd: undefined })
    },

    handleFinish ({ id = -1 }) {
      if (id === -1) return false
      const { $axios, $get, $message, refresh } = this
      const res = $axios.put(`api/assetsInventoryPlan/${id}`).then(res => res).catch(e => false)
      if ($get(res, 'data.code') !== '000000') return $message.error($get(res, 'data.mesg', '请稍后再试'))
      refresh()
      $message.info('操作成功')
    },

    handleDel ({ id = -1 }) {
      if (id === -1) return false
      const { delPlan } = this
      this.$confirm({
        centered: true,
        maskClosable: true,
        title: '提示',
        content: '确定删除？',
        onOk () {
          delPlan(id)
        }
      })
    },

    async delPlan (id) {
      const { $axios, $get, $message, refresh } = this
      const res = await $axios.delete(`api/assetsInventoryPlan/${id}`).then(res => res).catch(e => false)
      if ($get(res, 'data.code') !== '000000') return $message.error($get(res, 'data.mesg', '请稍后再试'))
      refresh()
      $message.info('操作成功')
    },

    /**
     * 查看详情，跳转到详情页
     * @param {Boolean} isDetail 是否点击查看按钮，是则默认切换到数据明细
     */
    showDetail (item, isDetail = false) {
      this.$router.push(`/property/plan/child/detail/${this.name}/${this.id}/${item.name}/${item.id}/${isDetail}`)
    },

    async showDataDetail ({ inventoryIds = '' }) {
      const { $axios, targetList, $get, detailCount } = this
      this.$toggleSending(1)
      targetList.splice(0)
      detailCount.splice(0)
      const list = await $axios.post('api/assetsInventory/queryPlanDetail', { inventoryIds })
        .then(res => $get(res, 'data.data', []).map(i => {
          const data = {}
          const keys = ['deptName', 'userName']
          keys.forEach(k => { if (!i[k]) data[k] = '-' })
          return Object.assign(i, data)
        }))
        .catch(e => ({}))
      targetList.push(...list.filter(i => i.goodsName !== '总计'))
      detailCount.push(...list.filter(i => i.goodsName === '总计'))
      this.$toggleSending()

      this.showDataModal = true
    },

    handleAdd () {
      if (process.client) {
        const tempData = JSON.parse(sessionStorage.getItem('temp_new_plan_child') || '{}')
        delete tempData[`${this.name}${this.id}`]
        sessionStorage.setItem('temp_new_plan_child', JSON.stringify(tempData))
      }
      this.$router.push(`/property/plan/child/add/${this.name}/${this.id}`)
    },

    refresh (name = 'table') {
      const table = this.$refs[name]
      table && table.refresh && table.refresh()
    },

    handlePage (p) {
      this.$handlePage(p)
    }
  }
}
</script>

<style lang="less" scoped>
  .action-container {
    .Flex;
    .Flex-justify-spacebetween;
  }

  /deep/ .ant-table-footer {
    border: 0 !important;
    padding: 0;
    margin-top: -1px;
    margin-right: -1px;
    margin-left: -1px;
  }

</style>
